﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using YJYpublicClass;

namespace 焱信引导检测
{
    static class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll ", SetLastError = true)]
        static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        ///// </summary>
        ///// <param name="hWnd">窗口句柄</param>
        ///// <param name="cmdShow">指示窗口如何被显示</param>
        ///// <returns>如果窗体之前是可见，返回值为非零；如果窗体之前被隐藏，返回值为零</returns>
        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        public const int SW_RESTORE = 9;
        public static IntPtr formhwnd;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process currentproc = Process.GetCurrentProcess();
            string processName = currentproc.ProcessName;
            Process[] processcollection = Process.GetProcessesByName(currentproc.ProcessName.Replace(".vshost", string.Empty));
            //  该程序已经运行，
            if (processcollection.Length > 1)
            {

                foreach (Process process in processcollection)
                {
                    if (process.Id != currentproc.Id)
                    {
                        // 如果进程的句柄为0，即代表没有找到该窗体，即该窗体隐藏的情况时
                        if (process.MainWindowHandle.ToInt32() == 0)
                        {
                            // 获得窗体句柄
                            formhwnd = FindWindow(null, "Form1"); // Form1是指主窗口的text值
                            // 重新显示该窗体并切换到带入到前台
                            ShowWindow(formhwnd, SW_RESTORE);
                            SwitchToThisWindow(formhwnd, true);
                        }
                        else
                        {
                            // 如果窗体没有隐藏，就直接切换到该窗体并带入到前台
                            // 因为窗体除了隐藏到托盘，还可以最小化
                            SwitchToThisWindow(process.MainWindowHandle, true);
                        }
                    }
                }
                LogHelper.Info("检测到程序运行，不启动");
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
              
        }
    }
}
